//
//  detect.c
//  FastPRDemo
//
//  Created by fanwenjie on 2017/6/3.
//  Copyright © 2017年 fanwenjie. All rights reserved.
//

#include "canny.h"
#include "detect.h"
#include "adaboost.h"
#include <stdlib.h>

///边缘定位
static Rect EdgeDetect(unsigned char *thresholdImage,short width, short height, unsigned int minSaltus, float edgeRatio)
{
    Rect result = { 0 , 0 ,width, height};
    short halfHeight = height >> 1, halfWidth = width >> 1;
    unsigned int rowSaltus[height];
    for(int i = 0; i < height; ++i)
    {
        unsigned char *src = thresholdImage + i * width;
        rowSaltus[i] = 0;
        for(int j = 1;j < width; ++j)
        {
            rowSaltus[i] += src[j] != src[j - 1];
        }
    }
    for(int i = height - 2;i > 0; --i)
    {
        if(rowSaltus[i] > minSaltus || (rowSaltus[i + 1] > minSaltus && rowSaltus[i - 1] > minSaltus))
        {
            int j = i;
            while (i > 0 && (rowSaltus[i] > minSaltus || (rowSaltus[i + 1] > minSaltus && rowSaltus[i - 1] > minSaltus)))
            {
                --i;
            }
            if((j - i) > halfHeight)
            {
                result.y = i;
                result.height = j - i + 1;
            }
        }
    }
    int minEdge = edgeRatio * height;
    for(int j = 0;j < halfWidth; ++j)
    {
        int sum = 0;
        for(int i = result.y;i < result.y + result.height; ++i)
        {
            sum += thresholdImage[i * width + j] != 0;
        }
        if(sum > minEdge)
        {
            result.x = j;
            break;
        }
    }
    for(int j = width - 1;j > halfWidth; --j)
    {
        int sum = 0;
        for(int i = result.y;i < result.y + result.height; ++i)
        {
            sum += thresholdImage[i * width + j] != 0;
        }
        if(sum > minEdge)
        {
            result.width = j - result.x;
            break;
        }
    }
    return result;
}


Rect Detect(const unsigned char *gray, const short width, const short height)
{
    Rect result = ObjectDetect(gray ,width, height);
    if(*(unsigned long long *)&result)
    {
        
        const short smallWidth = result.width , smallHeight = result.height;
        unsigned char *buffer = (unsigned char *)malloc(smallWidth * smallHeight * 2);
        unsigned char *smallImage = buffer, *thresholdImage = buffer + smallWidth * smallHeight;
        CropImage(gray, smallImage, width, smallWidth, smallHeight, result.x, result.y);
        Canny(smallImage, thresholdImage, smallWidth, smallHeight, 16, 32);
        Rect rect = EdgeDetect(thresholdImage, smallWidth, smallHeight, 8, 0.25);
        result.x += rect.x;
        result.y += rect.y;
        result.width = rect.width;
        result.height = rect.height;
        free(buffer);
    }
    return result;
}





